package com.cskaoyan.service.wx.impl;

import com.cskaoyan.bean.BaseRespVo;
import com.cskaoyan.bean.GenericData;
import com.cskaoyan.bean.po.*;
import com.cskaoyan.bean.wx.order.*;
import com.cskaoyan.config.exception.LoginAuthenException;
import com.cskaoyan.mapper.*;
import com.cskaoyan.mapper.wx.WxMarketOrderMapper;
import com.cskaoyan.service.wx.WxCartService;
import com.cskaoyan.service.wx.WxOrderService;
import com.cskaoyan.util.UserIdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author LiangRuiJiang
 * @since 2022/06/08  14:27
 */
@Service
public class WxOrderServiceImpl implements WxOrderService {

    @Autowired
    WxMarketOrderMapper wxMarketOrderMapper;

    @Autowired
    MarketOrderMapper marketOrderMapper;

    @Autowired
    MarketAftersaleMapper marketAftersaleMapper;

    @Autowired
    MarketAddressMapper marketAddressMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    WxCartService wxCartService;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketOrderGoodsMapper marketOrderGoodsMapper;

    @Autowired
    MarketCommentMapper marketCommentMapper;

    @Override
    public GenericData<WxMarketOrderVo> queryOrderList(Short showType, Integer page, Integer limit, Integer userId) {
        PageHelper.startPage(page, limit);

        List<WxMarketOrderVo> marketOrderVoList = wxMarketOrderMapper.selectWxMarketOrderVo(showType, userId);

        PageInfo pageInfo = new PageInfo(marketOrderVoList);

        return GenericData.data2(pageInfo, marketOrderVoList);
    }

    @Override
    public OrderDetailVo queryOrderDetail(Integer orderId, Integer userId) {

        List<WxOrderGoodsDetail> wxOrderGoodsDetails = wxMarketOrderMapper.selectOrderGoodsDetail(orderId);
        WxOrderInfo wxOrderInfo = wxMarketOrderMapper.selectWxOrderInfo(orderId, userId);

        OrderDetailVo orderDetailVo = new OrderDetailVo();
        orderDetailVo.setExpressInfo(new String[0]);
        orderDetailVo.setOrderGoods(wxOrderGoodsDetails);
        orderDetailVo.setOrderInfo(wxOrderInfo);
        return orderDetailVo;
    }

    @Override
    @Transactional
    public void UpdateOrderStatus(Integer orderId, String methodName) {
        // MarketOrder marketOrderOld = marketOrderMapper.selectByPrimaryKey(orderId);
        MarketOrder marketOrder = new MarketOrder();
        if (methodName.equals("refund")) {
            //  202表示申请退款
            marketOrder.setOrderStatus((short) 202);
            marketOrder.setRefundTime(new Date());
            // marketOrder.setRefundAmount(marketOrderOld.getActualPrice());
            // marketOrder.setRefundType();
        } else if (methodName.equals("confirm")) {
            // 401 表示确认收货
            marketOrder.setOrderStatus((short) 401);
            int comments = marketOrderGoodsMapper.selectGoodsByOrderId(orderId);
            marketOrder.setComments((short)comments);
            marketOrder.setConfirmTime(new Date());
            marketOrder.setEndTime(new Date());
        }
        marketOrder.setUpdateTime(new Date());
        MarketOrderExample example = new MarketOrderExample();
        MarketOrderExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(orderId);
        marketOrderMapper.updateByExampleSelective(marketOrder, example);

    }

    @Override
    @Transactional
    public void createAfterSaleRecord(Integer orderId) {
        // 根据订单状态创建售后信息
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);

        MarketAftersale aftersale = new MarketAftersale();
        // 售后编号
        Long millis = System.currentTimeMillis();
        aftersale.setAftersaleSn(millis.toString());

        aftersale.setOrderId(marketOrder.getId());
        aftersale.setUserId(marketOrder.getUserId());
        if (marketOrder.getOrderStatus() != 401 && marketOrder.getOrderStatus() != 402) {
            //未收货退款
            aftersale.setType((short) 0);
        } else if (marketOrder.getOrderStatus() == 401) {
            //已收货，退款
            aftersale.setType((short) 1);
        } else {
            //退货退款
            aftersale.setType((short) 2);
        }
        aftersale.setAmount(marketOrder.getActualPrice());
        // 售后状态 0是可申请，1是用户已申请，2是管理员审核通过，3是管理员退款成功，4是管理员审核拒绝，5是用户已取消'
        aftersale.setStatus((short) 0);
        aftersale.setAddTime(new Date());
        marketAftersaleMapper.insertSelective(aftersale);
    }

    @Override
    @Transactional
    public BaseRespVo insertOrder(WxOrderSubmitBo wxOrderSubmitBo) throws LoginAuthenException {

        BaseRespVo<Object> baseRespVo = new BaseRespVo<>();
        //通过addressId查询address表中的数据
        MarketAddress marketAddress = marketAddressMapper.selectByPrimaryKey(wxOrderSubmitBo.getAddressId());

        //创建一个订单
        MarketOrder marketOrder = new MarketOrder();

        Integer userId = UserIdUtil.getUserIdFromSubjectThrowException();
        marketOrder.setUserId(userId);

        SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
        Date date = new Date();
        String orderSn = format.format(date) ;
        marketOrder.setOrderSn(orderSn);

        marketOrder.setOrderStatus((short) 101);

        marketOrder.setAftersaleStatus((short) 0);

        marketOrder.setConsignee(marketAddress.getName());

        marketOrder.setMobile(marketAddress.getTel());

        marketOrder.setAddress(marketAddress.getAddressDetail());

        marketOrder.setMessage(wxOrderSubmitBo.getMessage());

        List<MarketCart> marketCarts = wxCartService.queryCartListByUserIdAndChecked(userId, true);
        if(marketCarts.size() == 0){
            Exception exception = new Exception("操作有误，请不要重复下单");
            baseRespVo.setData(exception);
            baseRespVo.setErrno(504);
            baseRespVo.setErrmsg("操作错误");
            return baseRespVo;
        }

        BigDecimal goodsTotalPrice = BigDecimal.ZERO;
        for (MarketCart marketCart : marketCarts) {

            goodsTotalPrice = goodsTotalPrice.add(marketCart.getPrice().multiply(new BigDecimal(Integer.toString(marketCart.getNumber()))));

        }
        marketOrder.setGoodsPrice(goodsTotalPrice);

        marketOrder.setFreightPrice(BigDecimal.ZERO);

        BigDecimal couponPrice = BigDecimal.ZERO;

        if(wxOrderSubmitBo.getCouponId() != 0){
            MarketCoupon marketCoupon = marketCouponMapper.selectByPrimaryKey(wxOrderSubmitBo.getCouponId());
            couponPrice = (marketCoupon.getDiscount());
        }
        marketOrder.setCouponPrice(couponPrice);

        marketOrder.setIntegralPrice(BigDecimal.ZERO);

        marketOrder.setGrouponPrice(BigDecimal.ZERO);

        marketOrder.setOrderPrice(goodsTotalPrice.add(BigDecimal.ZERO).subtract(couponPrice));

        marketOrder.setActualPrice(marketOrder.getOrderPrice().subtract(BigDecimal.ZERO));

        marketOrder.setAddTime(new Date());

        marketOrder.setDeleted(false);

        marketOrderMapper.insertSelective(marketOrder);

        WxOrderSubmitVo wxOrderSubmitVo = new WxOrderSubmitVo();
        wxOrderSubmitVo.setOrderId(marketOrder.getId());
        wxOrderSubmitVo.setGrouponLinkId(wxOrderSubmitBo.getGrouponLinkId());

        //创建订单用户关系表
        MarketOrderGoods marketOrderGoods = new MarketOrderGoods();
        for (MarketCart marketCart : marketCarts) {
            marketOrderGoods.setGoodsId(marketCart.getGoodsId());

            marketOrderGoods.setOrderId(marketOrder.getId());

            marketOrderGoods.setGoodsName(marketCart.getGoodsName());

            marketOrderGoods.setGoodsSn(marketCart.getGoodsSn());

            marketOrderGoods.setProductId(marketCart.getProductId());

            marketOrderGoods.setNumber(Short.parseShort(marketCart.getNumber().toString()));

            marketOrderGoods.setPrice(marketCart.getPrice());

            marketOrderGoods.setSpecifications(marketCart.getSpecifications());

            marketOrderGoods.setPicUrl(marketCart.getPicUrl());

            marketOrderGoods.setComment(0);

            marketOrderGoods.setAddTime(new Date());

            marketOrderGoods.setUpdateTime(new Date());

            marketOrderGoods.setDeleted(false);

            marketOrderGoods.setId(null);

            marketOrderGoodsMapper.insertSelective(marketOrderGoods);

        }


        //通过cartId 逻辑删除cart表中的数据
        for (MarketCart marketCart : marketCarts) {
            marketCart.setDeleted(true);
            marketCartMapper.updateByPrimaryKey(marketCart);
        }


        //通过userCouponId去market_coupon_user表中改变用户的优惠券使用状态
        if(wxOrderSubmitBo.getCouponId() != 0){
            MarketCouponUser marketCouponUser = new MarketCouponUser();
            marketCouponUser.setId(wxOrderSubmitBo.getUserCouponId());
            marketCouponUser.setStatus((short) 1);
            marketCouponUserMapper.updateByPrimaryKeySelective(marketCouponUser);
        }
        baseRespVo.setData(wxOrderSubmitVo);
        baseRespVo.setErrno(0);
        baseRespVo.setErrmsg("成功");
        return baseRespVo;
    }

    @Override
    public void update(MarketOrder marketOrder) {

        marketOrder.setOrderStatus((short) 201);

        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);

    }
    public MarketOrderGoods queryOrderGoods(Integer orderId, Integer goodsId) {
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        criteria.andGoodsIdEqualTo(goodsId);
        criteria.andDeletedEqualTo(false);
        List<MarketOrderGoods> marketOrderGoods = marketOrderGoodsMapper.selectByExample(example);
        MarketOrderGoods marketOrderGoodsReturn = null;
        if (marketOrderGoods != null && marketOrderGoods.size() == 1) {
            marketOrderGoodsReturn = marketOrderGoods.get(0);
        }
        return marketOrderGoodsReturn;
    }

    @Override
    @Transactional
    public void createOrderComment(OrderCommentBo orderCommentBo,Integer userId) {
        MarketComment comment = new MarketComment();
        comment.setAddTime(new Date());
        // 0表示商品评论
        comment.setType((byte)0);
        // comment.setValueId();
        comment.setContent(orderCommentBo.getContent());
        comment.setHasPicture(orderCommentBo.getHasPicture());
        comment.setPicUrls(orderCommentBo.getPicUrls());
        comment.setStar(orderCommentBo.getStar());
        comment.setUserId(userId);
        int goodsId = marketOrderGoodsMapper.selectGoodsIdByPrimaryKey(orderCommentBo.getOrderGoodsId());
        comment.setValueId(goodsId);
        marketCommentMapper.insertSelectiveReturnPrimaryKey(comment);
        // 修改订单评论状态
        MarketOrderGoods record = new MarketOrderGoods();
        record.setComment(comment.getId());
        //更新订单商品关系表中评论数据
        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andIdEqualTo(orderCommentBo.getOrderGoodsId());
        marketOrderGoodsMapper.updateByExampleSelective(record, example);
        //更新订单表中待评论商品的数量
        int orderId = marketOrderGoodsMapper.selectOrderIDByPrimaryKey(orderCommentBo.getOrderGoodsId());
        MarketOrder marketOrder = marketOrderMapper.selectByPrimaryKey(orderId);
        Short comments = marketOrder.getComments();
        comments --;
        marketOrder.setComments(comments);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

    @Override
    @Transactional
    public void deleteOrder(Integer orderId) {
        MarketOrder record = new MarketOrder();
        record.setId(orderId);
        record.setUpdateTime(new Date());
        record.setDeleted(true);
        marketOrderMapper.updateByPrimaryKeySelective(record);
        MarketOrderGoods orderGoods = new MarketOrderGoods();
        orderGoods.setDeleted(true);
        orderGoods.setOrderId(orderId);
        orderGoods.setUpdateTime(new Date());

        MarketOrderGoodsExample example = new MarketOrderGoodsExample();
        MarketOrderGoodsExample.Criteria criteria = example.createCriteria();
        criteria.andOrderIdEqualTo(orderId);
        marketOrderGoodsMapper.updateByExampleSelective(orderGoods,example);
    }

    @Override
    public void cancelOrder(Integer orderId) {
        MarketOrder marketOrder = new MarketOrder();
        marketOrder.setOrderStatus((short)102);
        marketOrder.setId(orderId);
        marketOrderMapper.updateByPrimaryKeySelective(marketOrder);
    }

}
